//
//  SortMD5Code.m
//  WJTheWishPro
//
//  Created by ENERGY on 2018/6/9.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "SortMD5Code.h"
#import <CommonCrypto/CommonDigest.h>

@implementation SortMD5Code
//传给服务器json串
- (NSString *)getJsonWithStrDic:(NSDictionary *)strDic withSignDic:(NSDictionary *)signDic{
    //得到str字符串
    NSString * strString = [self getStrstring:strDic];
    //得到sign字符串
    NSString * signString = [self getSignString:signDic];
    //传给服务器的json串
    NSString * json = [self transformStrString:strString withSignString:signString];
    return json;
}
//解析data，反替换然后解码，str解析成字典，重新构造字典后排序进行MD5加密
- (NSString *)encodeStringWithDictionary:(NSDictionary *)dic{
//    NSString * strResult = [dic objectForKey:@"str"];//接到的json串str字段
//    NSString * rebackStr = [self replaceBack:strResult];//反替换
//    NSString * decodeStr = [self dencode:rebackStr];//解码
//    NSDictionary * messageDic = [self dictionaryWithJsonString:decodeStr];//str解析成功
    NSDictionary * messageDic = [self getNSDictionaryData:dic];
    NSMutableDictionary *compareDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
    [compareDic setObject:@"80d709a97af1b8ab" forKey:@"merchantNo"];//构造新字典，用于后面进行比照
    //排序
    NSString * compareStr = [self compareSortKeyDictionary:compareDic];
    //MD5加密
    NSString * compareMd5Str = [self md5:compareStr];
#pragma mark - 这里查找接收的数据
    return compareMd5Str;
}
//得到解析字典
- (NSDictionary *)getNSDictionaryData:(NSDictionary *)dic{
    NSString * strResult = [dic objectForKey:@"str"];//接到的json串str字段
    NSString * rebackStr = [self replaceBack:strResult];//反替换
    NSString * decodeStr = [self dencode:rebackStr];//解码
    return [self dictionaryWithJsonString:decodeStr];//str解析成功
}

//得到str字符串
- (NSString *)getStrstring:(NSDictionary *)strDic{
    //排序
    NSString * sortString = [self newWayDic:strDic];
    //base64_encode操作
    NSString * encodeNewStr = [self base64EncodeString:sortString];
    //替换字符
    NSString * strString = [self replaceStr:encodeNewStr];
    return strString;
}
//得到sign字符串
- (NSString *)getSignString:(NSDictionary *)signDic{
    //排序
    NSString * signStr = [self newWayDic:signDic];
    //MD5加密
    NSString * md5Str = [self md5:signStr];
    return md5Str;
}
//传给服务器的json串
- (NSString *)transformStrString:(NSString *)strString withSignString:(NSString *)signString{
    NSDictionary * jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:strString, @"str", signString, @"sign", nil];
    NSString * tempJson = [self dictionaryToJson:jsonDic];
    return tempJson;
}
//jsonDic和sign合为一个dic（为上传头像准备的方法）
- (NSDictionary *)getUploadImgWithStrDic:(NSDictionary *)strDic withSignDic:(NSDictionary *)signDic{
    NSString * strStr = [self getStrstring:strDic];
    NSString * signStr = [self getSignString:strDic];
    return [NSDictionary dictionaryWithObjectsAndKeys:strStr, @"str", signStr, @"sign", nil];
}
//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

//排序
- (NSString *)newWayDic:(NSDictionary *)dict{
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
//    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
//    NSLog(@"valueArray:%@",valueArray);
    
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        NSString *keyValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:keyValue];
    }
    NSMutableString * sstr = [signArray componentsJoinedByString:@","];
    //插入
    [sstr insertString:@"{" atIndex:0];
    [sstr insertString:@"}" atIndex:sstr.length];
    return sstr;
}
//base64编码
- (NSString *)base64EncodeString:(NSString *)string{
    //1.先把字符串转换为二进制数据
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    //2.对二进制数据进行base64编码，返回编码后的字符串
    return [data base64EncodedStringWithOptions:0];
}
//字符替换
- (NSString *)replaceStr:(NSString *)origenalStr{
    NSArray * needToBeReplaceArr = [NSArray arrayWithObjects:@"+", @"/", @"=", @"d", @"D", @"b", @"B", @"W", @"w", nil];
    NSArray * replaceArr = [NSArray arrayWithObjects:@"!", @"@", @"#", @"*", @"^", @"%", @"&", @"(", @")", nil];
    NSMutableString * tempString = (NSMutableString *)origenalStr;
    
    for (int y = 0; y<needToBeReplaceArr.count; y++) {
        //取出需要替换的字符进行判断
        NSString * arrTempStr = needToBeReplaceArr[y];
        //遍历需要进行替换字符串
        for (int i = 0; i<[origenalStr length]; i++) {
            char tempChar = [tempString characterAtIndex:i];
            NSString * matchingStr = [NSString stringWithFormat:@"%c", tempChar];
            if ([matchingStr isEqualToString:arrTempStr]) {
                NSRange range = {i, 1};
                tempString = [tempString stringByReplacingCharactersInRange:range withString:replaceArr[y]];
            }
        }
    }
    return tempString;
}
//MD5加密
- (NSString *)md5:(NSString *)str {
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    return digest;
}
//字典转json格式字符串：
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}
//反替换
- (NSString *)replaceBack:(NSString *)getJsonStr{
    NSArray * needToBeReplaceArr = [NSArray arrayWithObjects:@"!", @"@", @"#", @"*", @"^", @"%", @"&", @"(", @")", nil];
    NSArray * replaceArr = [NSArray arrayWithObjects:@"+", @"/", @"=", @"d", @"D", @"b", @"B", @"W", @"w", nil];
    NSMutableString * tempString = (NSMutableString *)getJsonStr;
    for (int y = 0; y<needToBeReplaceArr.count; y++) {
        //取出需要替换的字符进行判断
        NSString * arrTempStr = needToBeReplaceArr[y];
        //遍历需要进行替换字符串
        for (int i = 0; i<[getJsonStr length]; i++) {
            char tempChar = [tempString characterAtIndex:i];
            NSString * matchingStr = [NSString stringWithFormat:@"%c", tempChar];
            if ([matchingStr isEqualToString:arrTempStr]) {
                NSRange range = {i, 1};
                tempString = [tempString stringByReplacingCharactersInRange:range withString:replaceArr[y]];
            }
        }
    }
    return tempString;
}

//json格式字符串转字典：
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//base64解码
- (NSString *)dencode:(NSString *)base64String{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}
//比照时排序
- (NSString *)compareSortKeyDictionary:(NSDictionary *)dict{
    NSMutableString * ns = nil;//数组一个元素
    NSMutableArray * totalValueArr = [NSMutableArray array];//装value的数组的value集合
//    NSMutableString * totalValueStr = nil;//装value的数组的json字符串
    NSMutableArray * tempTotalValueArr = [NSMutableArray array];;//临时
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
//    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
//    NSLog(@"valueArray:%@",valueArray);
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        if ([valueArray[i] isKindOfClass:[NSArray class]]) {
            
            if ([valueArray[i] count]>0) {
                for (int y = 0; y<[valueArray[i] count]; y++) {
                    //将所有的key放进数组
                    NSArray *insideAllKeyArray = [valueArray[i][y] allKeys];
                    //序列化器对数组进行排序的block 返回值为排序后的数组
                    NSArray *insideAfterSortKeyArray = [insideAllKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
                        NSComparisonResult resuest = [obj1 compare:obj2];
                        return resuest;
                    }];
//                    NSLog(@"insideAfterSortKeyArray:%@",insideAfterSortKeyArray);
                    //通过排列的key值获取value
                    NSMutableArray *insidevalueArray = [NSMutableArray array];
                    NSString *insideValueString = nil;
                    for (NSString *insideSortsing in insideAfterSortKeyArray) {
                        if ([insideSortsing isEqualToString:@""] || insideSortsing.length == 0) {
                            insideValueString = @"";
                            [insidevalueArray addObject:insideValueString];
                        }else{
                            insideValueString = [valueArray[i][y] objectForKey:insideSortsing];
                            [insidevalueArray addObject:insideValueString];
                        }
                    }
//                    NSLog(@"insidevalueArray:%@",insidevalueArray);
                    NSMutableArray *insideArray = [NSMutableArray array];
                    //body的value里面的一个数组
                    for (int t = 0 ; t < insideAfterSortKeyArray.count; t++) {
                        NSString *insideArraykeyValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",insideAfterSortKeyArray[t],insidevalueArray[t]];
                        [insideArray addObject:insideArraykeyValue];
                    }
                    ns = [insideArray componentsJoinedByString:@","];
                    [totalValueArr addObject:ns];
                }
                if (totalValueArr.count>0) {
                    //                        ns = [totalValueArr componentsJoinedByString:@","];
                    for (int a = 0; a<totalValueArr.count; a++) {
                        //                            // 插入字符串
                        //                            [str insertString:@"abc" atIndex:2];
                        NSMutableString * string = totalValueArr[a];
                        [string insertString:@"{" atIndex:0];
                        [string insertString:@"}" atIndex:string.length];
                        [tempTotalValueArr addObject:string];
                    }
                    ns = [tempTotalValueArr componentsJoinedByString:@","];
                    //插入
                    [ns insertString:@"[" atIndex:0];
                    [ns insertString:@"]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }else{
                    //插入
                    [ns insertString:@"[{" atIndex:0];
                    [ns insertString:@"}]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }
                
                
            }else{
                //在这判断数组是否为空
//                NSLog(@"走这里");
                NSMutableString *ns = [NSMutableString stringWithFormat:@""];
                //插入
                [ns insertString:@"[" atIndex:0];
                [ns insertString:@"]" atIndex:ns.length];
                [valueArray replaceObjectAtIndex:i withObject:ns];
            }
        }
        NSString *finalValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:finalValue];
    }
    NSMutableString * sstr = [signArray componentsJoinedByString:@","];
    //插入
    [sstr insertString:@"{" atIndex:0];
    [sstr insertString:@"}" atIndex:sstr.length];
    
    //判断字符串中是否包含"[{，如果有，替换为[{
    if([sstr rangeOfString:@"\"[{"].location != NSNotFound) {
        NSRange range2 = [sstr rangeOfString:@"\"[{"];
        [sstr replaceCharactersInRange:range2 withString:@"[{"]; //不是range2.location
        NSRange range3 = [sstr rangeOfString:@"}]\""];
        [sstr replaceCharactersInRange:range3 withString:@"}]"];
    }
    return sstr;
}
@end
